package com.example.asus.picsel;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.asus.picselector.activity.BaseActivity;
import com.example.asus.picselector.constants.Constants;
import com.example.asus.picselector.R;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class EduMyPictureSelectorActivity extends BaseActivity {
    public static final int REQUEST_PREVIEW = 0;
    public static final int REQUEST_CAMERA = 1;
    public static final int REQUEST_CODE_ASK_PERMISSIONS = 100;
    private GridView mGridView;
    private ImageButton mBtnBack;
    private Button mBtnSend;
    private PicTypeBtn mPicType;
    private PreviewBtn mPreviewBtn;
    private View mCatalogView;
    private ListView mCatalogListView;
    private List<PicItem> mAllItemList;
    private Map<String, List<PicItem>> mItemMap;
    private List<String> mCatalogList;
    private String mCurrentCatalog = "";
    private Uri mTakePictureUri;
    private boolean mSendOrigin = false;
    private int perWidth;
    private int perHeight;
    private String sendName;
    private boolean imgSelect;//是来自会话界面
    private boolean editheaad;//是否编辑头像
    private int imgMaxNumber = (Constants.PIC_MAX_NUMEBR - 1);
    private int imgMaxNumberSelect;
    private boolean isSelect;

    public EduMyPictureSelectorActivity() {
    }


    @Override
    protected void setContentView() {
        this.requestWindowFeature(1);
        this.setContentView(R.layout.activity_edu_picsel);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        if(getIntent()!=null){
            sendName = getIntent().getStringExtra(Constants.PIC_SEND);
            editheaad = getIntent().getBooleanExtra(Constants.PIC_EDIT, false);
            imgSelect = getIntent().getBooleanExtra(Constants.PIC_IMG_SELECT, false);
            imgMaxNumber = getIntent().getIntExtra(Constants.PIC_MAX, (Constants.PIC_MAX_NUMEBR - 1));
            imgMaxNumberSelect = getIntent().getIntExtra(Constants.PIC_MAX_SELECT, 0);
            isSelect = getIntent().getBooleanExtra(Constants.PIC_ISSELECT, false);
        }
        this.mGridView = (GridView)this.findViewById(R.id.gridlist);
        this.mBtnBack = (ImageButton)this.findViewById(R.id.back);
        this.mBtnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EduMyPictureSelectorActivity.this.finish();
            }
        });
        this.mBtnSend = (Button)this.findViewById(R.id.send);
        if(!TextUtils.isEmpty(sendName)){
            this.mBtnSend.setText(sendName+"");
        }
        this.mPicType = (PicTypeBtn)this.findViewById(R.id.pic_type);
        this.mPicType.init(this);
        this.mPicType.setEnabled(false);
        this.mPreviewBtn = (PreviewBtn)this.findViewById(R.id.preview);
        this.mPreviewBtn.init(this);
        this.mPreviewBtn.setEnabled(false);
        this.mCatalogView = this.findViewById(R.id.catalog_window);
        this.mCatalogListView = (ListView)this.findViewById(R.id.catalog_listview);
        if(editheaad){
            this.mBtnSend.setVisibility(View.GONE);
            this.mPreviewBtn.setVisibility(View.GONE);
        }
        String[] permissions = new String[]{"android.permission.READ_EXTERNAL_STORAGE"};
        if (!PermissionCheckUtil.checkPermissions(this, permissions)) {
            PermissionCheckUtil.requestPermissions(this, permissions, 100);
        } else {
            this.initView();
        }
    }

    @SuppressLint("WrongConstant")
    private void initView() {
        this.updatePictureItems();
        this.mGridView.setAdapter(new GridViewAdapter());
        this.mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(imgSelect){
                    intentPreView(position);
                }else {
                    if (position != 0) {
                        intentPreView(position);
                    }
                }

            }
        });
        this.mBtnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent data = new Intent();
                ArrayList<Uri> list = new ArrayList();
                Iterator var4 = EduMyPictureSelectorActivity.this.mItemMap.keySet().iterator();

                while(var4.hasNext()) {
                    String key = (String)var4.next();
                    Iterator var6 = ((List)EduMyPictureSelectorActivity.this.mItemMap.get(key)).iterator();

                    while(var6.hasNext()) {
                        PicItem item = (PicItem)var6.next();
                        if (item.selected) {
                            list.add(Uri.parse("file://" + item.uri));
                        }
                    }
                }

                data.putExtra("sendOrigin", EduMyPictureSelectorActivity.this.mSendOrigin);
                data.putExtra("android.intent.extra.RETURN_RESULT", list);
                EduMyPictureSelectorActivity.this.setResult(-1, data);
                EduMyPictureSelectorActivity.this.finish();
            }
        });
        this.mPicType.setEnabled(true);
        this.mPicType.setTextColor(this.getResources().getColor(R.color.white));
        this.mPicType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EduMyPictureSelectorActivity.this.mCatalogView.setVisibility(View.VISIBLE);
            }
        });
        this.mPreviewBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PicItemHolder.itemList = new ArrayList();
                Iterator var2 = EduMyPictureSelectorActivity.this.mItemMap.keySet().iterator();

                while(var2.hasNext()) {
                    String key = (String)var2.next();
                    Iterator var4 = ((List)EduMyPictureSelectorActivity.this.mItemMap.get(key)).iterator();

                    while(var4.hasNext()) {
                        PicItem item = (PicItem)var4.next();
                        if (item.selected) {
                            PicItemHolder.itemList.add(item);
                        }
                    }
                }

                PicItemHolder.itemSelectedList = null;
                Intent intent = new Intent(EduMyPictureSelectorActivity.this, EduMyPicturePreviewActivity.class);
                intent.putExtra("sendOrigin", EduMyPictureSelectorActivity.this.mSendOrigin);
                intent.putExtra("sendName", sendName);
                if(!imgSelect){
                    intent.putExtra("isSelect",true);
                    intent.putExtra("imgMaxNumberSelect",imgMaxNumberSelect);
                    intent.putExtra("imgMaxNumber",imgMaxNumber);
                }
                EduMyPictureSelectorActivity.this.startActivityForResult(intent, 0);
            }
        });
        this.mCatalogView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == 1 && EduMyPictureSelectorActivity.this.mCatalogView.getVisibility() == View.VISIBLE) {
                    EduMyPictureSelectorActivity.this.mCatalogView.setVisibility(View.GONE);
                }

                return true;
            }
        });
        this.mCatalogListView.setAdapter(new CatalogAdapter());
        this.mCatalogListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String catalog;
                if (position == 0) {
                    catalog = "";
                } else {
                    catalog = (String)EduMyPictureSelectorActivity.this.mCatalogList.get(position - 1);
                }

                if (catalog.equals(EduMyPictureSelectorActivity.this.mCurrentCatalog)) {
                    EduMyPictureSelectorActivity.this.mCatalogView.setVisibility(View.GONE);
                } else {
                    EduMyPictureSelectorActivity.this.mCurrentCatalog = catalog;
                    TextView textView = (TextView)view.findViewById(R.id.name);
                    EduMyPictureSelectorActivity.this.mPicType.setText(textView.getText().toString());
                    EduMyPictureSelectorActivity.this.mCatalogView.setVisibility(View.GONE);
                    ((CatalogAdapter)EduMyPictureSelectorActivity.this.mCatalogListView.getAdapter()).notifyDataSetChanged();
                    ((GridViewAdapter)EduMyPictureSelectorActivity.this.mGridView.getAdapter()).notifyDataSetChanged();
                }
            }
        });
        this.perWidth = ((WindowManager)((WindowManager)this.getSystemService("window"))).getDefaultDisplay().getWidth() / 3;
        this.perHeight = ((WindowManager)((WindowManager)this.getSystemService("window"))).getDefaultDisplay().getHeight() / 5;
    }

    public void intentPreView(int position){
        PicItemHolder.itemList = new ArrayList();
        if (EduMyPictureSelectorActivity.this.mCurrentCatalog.isEmpty()) {
            PicItemHolder.itemList.addAll(EduMyPictureSelectorActivity.this.mAllItemList);
            PicItemHolder.itemSelectedList = null;
        } else {
            PicItemHolder.itemList.addAll((Collection)EduMyPictureSelectorActivity.this.mItemMap.get(EduMyPictureSelectorActivity.this.mCurrentCatalog));
            PicItemHolder.itemSelectedList = new ArrayList();
            Iterator var6 = EduMyPictureSelectorActivity.this.mItemMap.keySet().iterator();

            label32:
            while(true) {
                String key;
                do {
                    if (!var6.hasNext()) {
                        break label32;
                    }

                    key = (String)var6.next();
                } while(key.equals(EduMyPictureSelectorActivity.this.mCurrentCatalog));

                Iterator var8 = ((List)EduMyPictureSelectorActivity.this.mItemMap.get(key)).iterator();

                while(var8.hasNext()) {
                    PicItem item = (PicItem)var8.next();
                    if (item.selected) {
                        PicItemHolder.itemSelectedList.add(item);
                    }
                }
            }
        }

        Intent intent = new Intent(EduMyPictureSelectorActivity.this, EduMyPicturePreviewActivity.class);

        intent.putExtra("editheaad",editheaad);
        if(imgSelect){
            intent.putExtra("index", position);
        }else {
            intent.putExtra("index", position - 1);
            intent.putExtra("isSelect",true);
            intent.putExtra("imgMaxNumberSelect",imgMaxNumberSelect);
            intent.putExtra("imgMaxNumber",imgMaxNumber);
        }
        intent.putExtra("sendOrigin", EduMyPictureSelectorActivity.this.mSendOrigin);
        intent.putExtra("sendName", sendName);
        EduMyPictureSelectorActivity.this.startActivityForResult(intent, 0);
    }

    @SuppressLint("WrongConstant")
    @Override
    @TargetApi(23)
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (Build.VERSION.SDK_INT >= 23 && this.checkSelfPermission("android.permission.READ_EXTERNAL_STORAGE") == 0) {
                this.initView();
            } else {
                Toast.makeText(this.getApplicationContext(), this.getString(R.string.edu_pic_sel_text_3), 0).show();
                this.finish();
            }
        }

        if (resultCode != 0) {
            if (resultCode == 1) {
                this.setResult(-1, data);
                this.finish();
            } else {
                switch(requestCode) {
                    case 0:
                        this.mSendOrigin = data.getBooleanExtra("sendOrigin", false);
                        ArrayList<PicItem> list = PicItemHolder.itemList;
                        if (list == null) {
                            return;
                        }

                        Iterator var9 = list.iterator();

                        while(var9.hasNext()) {
                            PicItem it = (PicItem)var9.next();
                            PicItem item = this.findByUri(it.uri);
                            if (item != null) {
                                item.selected = it.selected;
                            }
                        }

                        ((GridViewAdapter)this.mGridView.getAdapter()).notifyDataSetChanged();
                        ((CatalogAdapter)this.mCatalogListView.getAdapter()).notifyDataSetChanged();
                        this.updateToolbar();
                        break;
                    case 1:
                        if (this.mTakePictureUri != null) {
                            Intent datas = new Intent();
                            ArrayList<Uri> lists = new ArrayList();
                            PicItemHolder.itemList = new ArrayList();
                            PicItem item = new PicItem();
                            item.uri = this.mTakePictureUri.getPath();
                            PicItemHolder.itemList.add(item);
                            PicItemHolder.itemSelectedList = null;
                            if(editheaad){
                                //拍照结束跳到预览页
                                Intent intent = new Intent(this, EduMyPicturePreviewActivity.class);
                                intent.putExtra("editheaad",editheaad);
                                this.startActivityForResult(intent, 0);
                                MediaScannerConnection.scanFile(this, new String[]{this.mTakePictureUri.getPath()}, (String[])null, new MediaScannerConnection.OnScanCompletedListener() {
                                    public void onScanCompleted(String path, Uri uri) {
                                        EduMyPictureSelectorActivity.this.updatePictureItems();
                                    }
                                });
                            }else {
                                //拍照结束直接返回
                                lists.add(Uri.parse("file://" + item.uri));
                                datas.putExtra("sendOrigin", true);
                                datas.putExtra("android.intent.extra.RETURN_RESULT",lists);
                                EduMyPictureSelectorActivity.this.setResult(-1, datas);
                                MediaScannerConnection.scanFile(this, new String[]{this.mTakePictureUri.getPath()}, (String[])null, new MediaScannerConnection.OnScanCompletedListener() {
                                    public void onScanCompleted(String path, Uri uri) {
                                        EduMyPictureSelectorActivity.this.updatePictureItems();
                                    }
                                });
                                EduMyPictureSelectorActivity.this.finish();
                            }

                        }
                }

            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 4 && this.mCatalogView != null && this.mCatalogView.getVisibility() == View.VISIBLE) {
            this.mCatalogView.setVisibility(View.GONE);
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }


    @SuppressLint("WrongConstant")
    protected void requestCamera() {
        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        if (!path.exists()) {
            path.mkdirs();
        }

        String name = System.currentTimeMillis() + ".jpg";
        File file = new File(path, name);
        this.mTakePictureUri = Uri.fromFile(file);
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        @SuppressLint("WrongConstant") List<ResolveInfo> resInfoList = this.getPackageManager().queryIntentActivities(intent, 65536);
        if (resInfoList.size() <= 0) {
            Toast.makeText(this, this.getResources().getString(R.string.edu_pic_sel_text_4), Toast.LENGTH_SHORT).show();
        } else {
            Uri uri = null;

            try {
                uri = FileProvider.getUriForFile(this, this.getPackageName() + this.getString(R.string.rc_authorities_fileprovider), file);
            } catch (Exception var10) {
                var10.printStackTrace();
                throw new RuntimeException("Please check IMKit Manifest FileProvider config.");
            }

            Iterator var7 = resInfoList.iterator();

            while(var7.hasNext()) {
                ResolveInfo resolveInfo = (ResolveInfo)var7.next();
                String packageName = resolveInfo.activityInfo.packageName;
                this.grantUriPermission(packageName, uri, 2);
                this.grantUriPermission(packageName, uri, 1);
            }

            intent.putExtra("output", uri);
            this.startActivityForResult(intent, 1);
        }
    }

    private void updatePictureItems() {
        String[] projection = new String[]{"_data", "date_added"};
        String orderBy = "datetaken DESC";
        Cursor cursor = this.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, (String)null, (String[])null, orderBy);
        this.mAllItemList = new ArrayList();
        this.mCatalogList = new ArrayList();
        this.mItemMap = new ArrayMap();
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {
                    PicItem item = new PicItem();
                    item.uri = cursor.getString(0);
                    if (item.uri != null) {
                        File file = new File(item.uri);
                        if (file.exists() && file.length() != 0L) {
                            this.mAllItemList.add(item);
                            int last = item.uri.lastIndexOf("/");
                            if (last != -1) {
                                String catalog;
                                if (last == 0) {
                                    catalog = "/";
                                } else {
                                    int secondLast = item.uri.lastIndexOf("/", last - 1);
                                    catalog = item.uri.substring(secondLast + 1, last);
                                }

                                if (this.mItemMap.containsKey(catalog)) {
                                    ((List)this.mItemMap.get(catalog)).add(item);
                                } else {
                                    ArrayList<PicItem> itemList = new ArrayList();
                                    itemList.add(item);
                                    this.mItemMap.put(catalog, itemList);
                                    this.mCatalogList.add(catalog);
                                }
                            }
                        }
                    }
                } while(cursor.moveToNext());
            }

            cursor.close();
        }

    }

    private int getTotalSelectedNum() {
        int sum = 0;
        Iterator var2 = this.mItemMap.keySet().iterator();

        while(var2.hasNext()) {
            String key = (String)var2.next();
            Iterator var4 = ((List)this.mItemMap.get(key)).iterator();

            while(var4.hasNext()) {
                PicItem item = (PicItem)var4.next();
                if (item.selected) {
                    ++sum;
                }
            }
        }

        return sum;
    }

    private void updateToolbar() {
        int sum = this.getTotalSelectedNum();
        if (sum == 0) {
            this.mBtnSend.setEnabled(false);
            this.mBtnSend.setTextColor(this.getResources().getColor(R.color.color_18));
            if(!TextUtils.isEmpty(sendName)){
                this.mBtnSend.setText(sendName);
            }else {
                this.mBtnSend.setText(R.string.edu_pic_sel_text_1);
            }
            this.mPreviewBtn.setEnabled(false);
            this.mPreviewBtn.setText(R.string.edu_pic_sel_text_2);
        } else {
            if(isSelect){
                if (sum <= imgMaxNumber) {
                    this.mBtnSend.setEnabled(true);
                    this.mBtnSend.setTextColor(this.getResources().getColor(R.color.white));
                    if(!TextUtils.isEmpty(sendName)){
                        this.mBtnSend.setText(String.format(sendName+"(%d/"+imgMaxNumber+")", sum));
                    }else {
                        this.mBtnSend.setText(String.format("发送(%d/"+imgMaxNumber+")", sum));
                    }
                    this.mPreviewBtn.setEnabled(true);
                    this.mPreviewBtn.setText(String.format(this.getResources().getString(R.string.edu_pic_sel_text_6), sum));
                }
            }else {
                if (sum <= 9) {
                    this.mBtnSend.setEnabled(true);
                    this.mBtnSend.setTextColor(this.getResources().getColor(R.color.white));
                    if(!TextUtils.isEmpty(sendName)){
                        this.mBtnSend.setText(String.format(sendName+"(%d/9)", sum));
                    }else {
                        this.mBtnSend.setText(String.format(this.getResources().getString(R.string.edu_pic_sel_text_5), sum));
                    }
                    this.mPreviewBtn.setEnabled(true);
                    this.mPreviewBtn.setText(String.format(this.getResources().getString(R.string.edu_pic_sel_text_6), sum));
                }
            }
        }

    }

    private PicItem getItemAt(int index) {
        int sum = 0;
        Iterator var3 = this.mItemMap.keySet().iterator();

        while(var3.hasNext()) {
            String key = (String)var3.next();

            for(Iterator var5 = ((List)this.mItemMap.get(key)).iterator(); var5.hasNext(); ++sum) {
                PicItem item = (PicItem)var5.next();
                if (sum == index) {
                    return item;
                }
            }
        }

        return null;
    }

    private PicItem getItemAt(String catalog, int index) {
        if (!this.mItemMap.containsKey(catalog)) {
            return null;
        } else {
            int sum = 0;

            for(Iterator var4 = ((List)this.mItemMap.get(catalog)).iterator(); var4.hasNext(); ++sum) {
                PicItem item = (PicItem)var4.next();
                if (sum == index) {
                    return item;
                }
            }

            return null;
        }
    }

    private PicItem findByUri(String uri) {
        Iterator var2 = this.mItemMap.keySet().iterator();

        while(var2.hasNext()) {
            String key = (String)var2.next();
            Iterator var4 = ((List)this.mItemMap.get(key)).iterator();

            while(var4.hasNext()) {
                PicItem item = (PicItem)var4.next();
                if (item.uri.equals(uri)) {
                    return item;
                }
            }
        }

        return null;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch(requestCode) {
            case 100:
                if (grantResults[0] == 0) {
                    if (permissions[0].equals("android.permission.READ_EXTERNAL_STORAGE")) {
                        this.initView();
                    } else if (permissions[0].equals("android.permission.CAMERA")) {
                        this.requestCamera();
                    }
                } else if (permissions[0].equals("android.permission.CAMERA")) {
                    Toast.makeText(this.getApplicationContext(), this.getString(R.string.edu_pic_sel_text_3), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this.getApplicationContext(), this.getString(R.string.edu_pic_sel_text_3), Toast.LENGTH_SHORT).show();
                    this.finish();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }

    }

    @Override
    protected void onDestroy() {
        PicItemHolder.itemList = null;
        PicItemHolder.itemSelectedList = null;
        super.onDestroy();
    }

    public static class PicItemHolder {
        public static ArrayList<PicItem> itemList;
        public static ArrayList<PicItem> itemSelectedList;

        public PicItemHolder() {
        }
    }

    @SuppressLint("AppCompatCustomView")
    public static class SelectBox extends ImageView {
        private boolean mIsChecked;

        public SelectBox(Context context, AttributeSet attrs) {
            super(context, attrs);
            this.setImageResource(R.drawable.rc_select_check_nor);
        }

        public void setChecked(boolean check) {
            this.mIsChecked = check;
            this.setImageResource(this.mIsChecked ? R.drawable.rc_select_check_sel : R.drawable.rc_select_check_nor);
        }

        public boolean getChecked() {
            return this.mIsChecked;
        }
    }

    public static class PreviewBtn extends LinearLayout {
        private TextView mText;

        public PreviewBtn(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public void init(Activity root) {
            this.mText = (TextView)root.findViewById(R.id.preview_text);
        }

        public void setText(int id) {
            this.mText.setText(id);
        }

        public void setText(String text) {
            this.mText.setText(text);
        }

        @Override
        public void setEnabled(boolean enabled) {
            super.setEnabled(enabled);
            int color = enabled ? R.color.white : R.color.color_18;
            this.mText.setTextColor(this.getResources().getColor(color));
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (this.isEnabled()) {
                switch(event.getAction()) {
                    case 0:
                        this.mText.setVisibility(View.INVISIBLE);
                        break;
                    case 1:
                        this.mText.setVisibility(View.VISIBLE);
                }
            }

            return super.onTouchEvent(event);
        }
    }

    public static class PicTypeBtn extends LinearLayout {
        TextView mText;

        public PicTypeBtn(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public void init(Activity root) {
            this.mText = (TextView)root.findViewById(R.id.type_text);
        }

        public void setText(String text) {
            this.mText.setText(text);
        }

        public void setTextColor(int color) {
            this.mText.setTextColor(color);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if (this.isEnabled()) {
                switch(event.getAction()) {
                    case 0:
                        this.mText.setVisibility(View.INVISIBLE);
                        break;
                    case 1:
                        this.mText.setVisibility(View.VISIBLE);
                }
            }

            return super.onTouchEvent(event);
        }
    }

    public static class PicItem implements Parcelable {
        String uri;
        boolean selected;
        public static final Creator<PicItem> CREATOR = new Creator<PicItem>() {
            @Override
            public PicItem createFromParcel(Parcel source) {
                return new PicItem(source);
            }

            @Override
            public PicItem[] newArray(int size) {
                return new PicItem[size];
            }
        };

        @Override
        public int describeContents() {
            return 0;
        }

        public PicItem() {
        }

        public PicItem(Parcel in) {
            this.uri = ParcelUtils.readFromParcel(in);
            this.selected = ParcelUtils.readIntFromParcel(in) == 1;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            ParcelUtils.writeToParcel(dest, this.uri);
            ParcelUtils.writeToParcel(dest, this.selected ? 1 : 0);
        }
    }

    private class CatalogAdapter extends BaseAdapter {
        private LayoutInflater mInflater = EduMyPictureSelectorActivity.this.getLayoutInflater();

        public CatalogAdapter() {
        }

        @Override
        public int getCount() {
            return EduMyPictureSelectorActivity.this.mItemMap.size() + 1;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return (long)position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            ViewHolder holder;
            if (convertView == null) {
                view = this.mInflater.inflate(R.layout.edu_picsel_catalog_listview, parent, false);
                holder = new ViewHolder();
                holder.image = (ImageView)view.findViewById(R.id.image);
                holder.name = (TextView)view.findViewById(R.id.name);
                holder.number = (TextView)view.findViewById(R.id.number);
                holder.selected = (ImageView)view.findViewById(R.id.selected);
                view.setTag(holder);
            } else {
                holder = (ViewHolder)convertView.getTag();
            }

            String path;
            if (holder.image.getTag() != null) {
                path = (String)holder.image.getTag();
                AlbumBitmapCacheHelper.getInstance().removePathFromShowlist(path);
            }

            int num = 0;
            boolean showSelected = false;
            String name;
            Bitmap bitmap;
            BitmapDrawable bd;
            if (position == 0) {
                if (EduMyPictureSelectorActivity.this.mItemMap.size() == 0) {
                    holder.image.setImageResource(R.drawable.rc_picsel_empty_pic);
                } else {
                    path = ((PicItem)((List)EduMyPictureSelectorActivity.this.mItemMap.get(EduMyPictureSelectorActivity.this.mCatalogList.get(0))).get(0)).uri;
                    AlbumBitmapCacheHelper.getInstance().addPathToShowlist(path);
                    holder.image.setTag(path);
                    bitmap = AlbumBitmapCacheHelper.getInstance().getBitmap(path, EduMyPictureSelectorActivity.this.perWidth, EduMyPictureSelectorActivity.this.perHeight, new AlbumBitmapCacheHelper.ILoadImageCallback() {
                        @Override
                        public void onLoadImageCallBack(Bitmap bitmap, String path1, Object... objects) {
                            if (bitmap != null) {
                                BitmapDrawable bd = new BitmapDrawable(EduMyPictureSelectorActivity.this.getResources(), bitmap);
                                View v = EduMyPictureSelectorActivity.this.mGridView.findViewWithTag(path1);
                                if (v != null) {
                                    v.setBackgroundDrawable(bd);
                                    CatalogAdapter.this.notifyDataSetChanged();
                                }

                            }
                        }
                    }, new Object[]{position});
                    if (bitmap != null) {
                        bd = new BitmapDrawable(EduMyPictureSelectorActivity.this.getResources(), bitmap);
                        holder.image.setBackgroundDrawable(bd);
                    } else {
                        holder.image.setBackgroundResource(R.drawable.rc_grid_image_default);
                    }
                }

                name = EduMyPictureSelectorActivity.this.getResources().getString(R.string.edu_pic_sel_text_7);
                holder.number.setVisibility(View.GONE);
                showSelected = EduMyPictureSelectorActivity.this.mCurrentCatalog.isEmpty();
            } else {
                path = ((PicItem)((List)EduMyPictureSelectorActivity.this.mItemMap.get(EduMyPictureSelectorActivity.this.mCatalogList.get(position - 1))).get(0)).uri;
                name = (String)EduMyPictureSelectorActivity.this.mCatalogList.get(position - 1);
                num = ((List)EduMyPictureSelectorActivity.this.mItemMap.get(EduMyPictureSelectorActivity.this.mCatalogList.get(position - 1))).size();
                holder.number.setVisibility(View.VISIBLE);
                showSelected = name.equals(EduMyPictureSelectorActivity.this.mCurrentCatalog);
                AlbumBitmapCacheHelper.getInstance().addPathToShowlist(path);
                holder.image.setTag(path);
                bitmap = AlbumBitmapCacheHelper.getInstance().getBitmap(path, EduMyPictureSelectorActivity.this.perWidth, EduMyPictureSelectorActivity.this.perHeight, new AlbumBitmapCacheHelper.ILoadImageCallback() {
                    @Override
                    public void onLoadImageCallBack(Bitmap bitmap, String path1, Object... objects) {
                        if (bitmap != null) {
                            BitmapDrawable bd = new BitmapDrawable(EduMyPictureSelectorActivity.this.getResources(), bitmap);
                            View v = EduMyPictureSelectorActivity.this.mGridView.findViewWithTag(path1);
                            if (v != null) {
                                v.setBackgroundDrawable(bd);
                                CatalogAdapter.this.notifyDataSetChanged();
                            }

                        }
                    }
                }, new Object[]{position});
                if (bitmap != null) {
                    bd = new BitmapDrawable(EduMyPictureSelectorActivity.this.getResources(), bitmap);
                    holder.image.setBackgroundDrawable(bd);
                } else {
                    holder.image.setBackgroundResource(R.drawable.rc_grid_image_default);
                }
            }

            holder.name.setText(name);
            holder.number.setText(String.format(EduMyPictureSelectorActivity.this.getResources().getString(R.string.edu_pic_sel_text_8), num));
            holder.selected.setVisibility(showSelected ? View.VISIBLE : View.INVISIBLE);
            return view;
        }

        private class ViewHolder {
            ImageView image;
            TextView name;
            TextView number;
            ImageView selected;

            private ViewHolder() {
            }
        }
    }

    private class GridViewAdapter extends BaseAdapter {
        private LayoutInflater mInflater = EduMyPictureSelectorActivity.this.getLayoutInflater();

        public GridViewAdapter() {
        }

        @Override
        public int getCount() {
            int sum = 0;
            if(!imgSelect){
                sum = 1;
            }
            String key;
            if (EduMyPictureSelectorActivity.this.mCurrentCatalog.isEmpty()) {
                for(Iterator var2 = EduMyPictureSelectorActivity.this.mItemMap.keySet().iterator(); var2.hasNext(); sum += ((List)EduMyPictureSelectorActivity.this.mItemMap.get(key)).size()) {
                    key = (String)var2.next();
                }
            } else {
                sum += ((List)EduMyPictureSelectorActivity.this.mItemMap.get(EduMyPictureSelectorActivity.this.mCurrentCatalog)).size();
            }

            return sum;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return (long)position;
        }

        @Override
        @TargetApi(23)
        public View getView(int position, View convertView, ViewGroup parent) {
            if(imgSelect){
                final PicItem item;
                item = (PicItem)EduMyPictureSelectorActivity.this.mAllItemList.get(position);
                View view = convertView;
                final ViewHolder holder;
                if (convertView != null && convertView.getTag() != null) {
                    holder = (ViewHolder)convertView.getTag();
                } else {
                    view = this.mInflater.inflate(R.layout.edu_picsel_grid_items, parent, false);
                    holder = new ViewHolder();
                    holder.image = (ImageView)view.findViewById(R.id.image);
                    holder.mask = view.findViewById(R.id.mask);
                    holder.checkBox = (SelectBox)view.findViewById(R.id.checkbox);
                    view.setTag(holder);
                }

                String path;
                if (holder.image.getTag() != null) {
                    path = (String)holder.image.getTag();
                    AlbumBitmapCacheHelper.getInstance().removePathFromShowlist(path);
                }

                path = item.uri;
                AlbumBitmapCacheHelper.getInstance().addPathToShowlist(path);
                holder.image.setTag(path);
                Bitmap bitmap = AlbumBitmapCacheHelper.getInstance().getBitmap(path, EduMyPictureSelectorActivity.this.perWidth, EduMyPictureSelectorActivity.this.perHeight, new AlbumBitmapCacheHelper.ILoadImageCallback() {
                    @Override
                    public void onLoadImageCallBack(Bitmap bitmap, String path1, Object... objects) {
                        if (bitmap != null) {
                            BitmapDrawable bd = new BitmapDrawable(EduMyPictureSelectorActivity.this.getResources(), bitmap);
                            View v = EduMyPictureSelectorActivity.this.mGridView.findViewWithTag(path1);
                            if (v != null) {
                                v.setBackgroundDrawable(bd);
                            }

                        }
                    }
                }, new Object[]{position});
                if (bitmap != null) {
                    BitmapDrawable bd = new BitmapDrawable(EduMyPictureSelectorActivity.this.getResources(), bitmap);
                    holder.image.setBackgroundDrawable(bd);
                } else {
                    holder.image.setBackgroundResource(R.drawable.rc_grid_image_default);
                }

                holder.checkBox.setChecked(item.selected);
                holder.checkBox.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!holder.checkBox.getChecked() && EduMyPictureSelectorActivity.this.getTotalSelectedNum() == imgMaxNumber) {
                            Toast.makeText(EduMyPictureSelectorActivity.this.getApplicationContext(), "您最多只能选择"+imgMaxNumber+"张图片", Toast.LENGTH_SHORT).show();
                        } else {
                            holder.checkBox.setChecked(!holder.checkBox.getChecked());
                            item.selected = holder.checkBox.getChecked();
                            if (item.selected) {
                                holder.mask.setBackgroundColor(EduMyPictureSelectorActivity.this.getResources().getColor(R.color.color_20));
                            } else {
                                holder.mask.setBackgroundDrawable(EduMyPictureSelectorActivity.this.getResources().getDrawable(R.drawable.edu_sp_grid_mask));
                            }

                            EduMyPictureSelectorActivity.this.updateToolbar();
                        }
                    }
                });
                if (item.selected) {
                    holder.mask.setBackgroundColor(EduMyPictureSelectorActivity.this.getResources().getColor(R.color.color_20));
                } else {
                    holder.mask.setBackgroundDrawable(EduMyPictureSelectorActivity.this.getResources().getDrawable(R.drawable.edu_sp_grid_mask));
                }
                return view;
            }else {
                if (position == 0) {
                    View viewx = this.mInflater.inflate(R.layout.edu_picsel_grid_camera, parent, false);
                    ImageButton mask = (ImageButton)viewx.findViewById(R.id.camera_mask);
                    mask.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String[] permissions = new String[]{"android.permission.CAMERA"};
                            if (!PermissionCheckUtil.checkPermissions(EduMyPictureSelectorActivity.this, permissions)) {
                                PermissionCheckUtil.requestPermissions(EduMyPictureSelectorActivity.this, permissions, 100);
                            } else {
                                EduMyPictureSelectorActivity.this.requestCamera();
                            }
                        }
                    });
                    return viewx;
                } else {
                    final PicItem item;
                    if (EduMyPictureSelectorActivity.this.mCurrentCatalog.isEmpty()) {
                        item = (PicItem)EduMyPictureSelectorActivity.this.mAllItemList.get(position - 1);
                    } else {
                        item = EduMyPictureSelectorActivity.this.getItemAt(EduMyPictureSelectorActivity.this.mCurrentCatalog, position - 1);
                    }

                    View view = convertView;
                    final ViewHolder holder;
                    if (convertView != null && convertView.getTag() != null) {
                        holder = (ViewHolder)convertView.getTag();
                    } else {
                        view = this.mInflater.inflate(R.layout.edu_picsel_grid_items, parent, false);
                        holder = new ViewHolder();
                        holder.image = (ImageView)view.findViewById(R.id.image);
                        holder.mask = view.findViewById(R.id.mask);
                        holder.checkBox = (SelectBox)view.findViewById(R.id.checkbox);
                        view.setTag(holder);
                    }

                    String path;
                    if (holder.image.getTag() != null) {
                        path = (String)holder.image.getTag();
                        AlbumBitmapCacheHelper.getInstance().removePathFromShowlist(path);
                    }

                    path = item.uri;
                    AlbumBitmapCacheHelper.getInstance().addPathToShowlist(path);
                    holder.image.setTag(path);
                    Bitmap bitmap = AlbumBitmapCacheHelper.getInstance().getBitmap(path, EduMyPictureSelectorActivity.this.perWidth, EduMyPictureSelectorActivity.this.perHeight, new AlbumBitmapCacheHelper.ILoadImageCallback() {
                        @Override
                        public void onLoadImageCallBack(Bitmap bitmap, String path1, Object... objects) {
                            if (bitmap != null) {
                                BitmapDrawable bd = new BitmapDrawable(EduMyPictureSelectorActivity.this.getResources(), bitmap);
                                View v = EduMyPictureSelectorActivity.this.mGridView.findViewWithTag(path1);
                                if (v != null) {
                                    v.setBackgroundDrawable(bd);
                                }

                            }
                        }
                    }, new Object[]{position});
                    if (bitmap != null) {
                        BitmapDrawable bd = new BitmapDrawable(EduMyPictureSelectorActivity.this.getResources(), bitmap);
                        holder.image.setBackgroundDrawable(bd);
                    } else {
                        holder.image.setBackgroundResource(R.drawable.rc_grid_image_default);
                    }

                    holder.checkBox.setChecked(item.selected);
                    holder.checkBox.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!holder.checkBox.getChecked() && EduMyPictureSelectorActivity.this.getTotalSelectedNum() == imgMaxNumber) {
                                Toast.makeText(EduMyPictureSelectorActivity.this.getApplicationContext(), "您最多只能选择"+imgMaxNumber+"张图片", Toast.LENGTH_SHORT).show();
//                                if(isSelect){
//                                    Toast.makeText(EduMyPictureSelectorActivity.this.getApplicationContext(), "您已经选择了"+imgMaxNumberSelect+"张图片上传", Toast.LENGTH_SHORT).show();
//                                }else {
//                                    Toast.makeText(EduMyPictureSelectorActivity.this.getApplicationContext(), "您最多只能选择"+imgMaxNumber+"张图片", Toast.LENGTH_SHORT).show();
//                                }
                            } else {
                                holder.checkBox.setChecked(!holder.checkBox.getChecked());
                                item.selected = holder.checkBox.getChecked();
                                if (item.selected) {
                                    holder.mask.setBackgroundColor(EduMyPictureSelectorActivity.this.getResources().getColor(R.color.color_20));
                                } else {
                                    holder.mask.setBackgroundDrawable(EduMyPictureSelectorActivity.this.getResources().getDrawable(R.drawable.edu_sp_grid_mask));
                                }

                                EduMyPictureSelectorActivity.this.updateToolbar();
                            }
                        }
                    });
                    if (item.selected) {
                        holder.mask.setBackgroundColor(EduMyPictureSelectorActivity.this.getResources().getColor(R.color.color_20));
                    } else {
                        holder.mask.setBackgroundDrawable(EduMyPictureSelectorActivity.this.getResources().getDrawable(R.drawable.edu_sp_grid_mask));
                    }
                    if(editheaad){
                        holder.checkBox.setVisibility(View.GONE);
                    }
                    return view;
                }
            }

        }

        private class ViewHolder {
            ImageView image;
            View mask;
            SelectBox checkBox;

            private ViewHolder() {
            }
        }
    }
}